package com.alinesno.cloud.operation.cmdb.third.headth;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alinesno.cloud.operation.cmdb.common.constants.HealthCheckTypeEnum;
import com.alinesno.cloud.operation.cmdb.entity.ResourceHeadthEntity;
import com.alinesno.cloud.operation.cmdb.entity.ResourceHeadthLoggerEntity;
import com.alinesno.cloud.operation.cmdb.service.ResourceHeadthService;


/**
 * 定时检查服务健康状态(每半个小时做一次检查)
 * @author WeiXiaoJin
 * @since 2019年5月17日 上午6:23:06
 */
@Component
public class NetworkHealthJob {

	private static final Logger logger = LoggerFactory.getLogger(NetworkHealthJob.class);

	@Autowired
	private ResourceHeadthService resourceHeadthService ; 
	
	private EchoClient client = new EchoClient() ; 

	@Scheduled(cron = "0 0/1 * * * ?")
	public void doJob() {
		logger.debug("=====> 检查服务运行状态") ; 

		List<ResourceHeadthEntity> list = resourceHeadthService.findAll() ; 
		for(ResourceHeadthEntity e : list) {
			this.checkHeadlth(e); ; 
		}
		
	}
	
	@Async("processExecutor")
	public void checkHeadlth(ResourceHeadthEntity headth) {
	
		logger.debug("=====> 检查服务{}运行状态" , headth) ; 
		ResourceHeadthLoggerEntity hLogger = new ResourceHeadthLoggerEntity(new Date() , headth.getId()) ; 
		
		if(HealthCheckTypeEnum.TCP.getValue().equalsIgnoreCase(headth.getCheckType())) {
			try {
				boolean b = client.connect(Integer.parseInt(headth.getTcpPort()) , headth.getTcpHost()) ;
				if(b) {
					// 更新最后检查时间
					headth.setLastHeadthTime(new Date());
					headth.setHasStatus(0);
				}
			} catch (NumberFormatException e) {
				logger.error("服务端口格式化错误:{}" , e.getMessage());
				headth.setHasStatus(1);
				hLogger.setErrorMessage(e.getMessage());
			} catch (Exception e) {
				logger.error("服务检查错误:{}" , e.getMessage());
				headth.setHasStatus(1);
				hLogger.setErrorMessage(e.getMessage());
			} finally {
				resourceHeadthService.updateHeadth(headth) ; 
				// 保存检查记录
				resourceHeadthService.saveHeadLogger(hLogger) ; 
			}
		}
	}
	
}
